## SBSTV have an API but it isn't for public use
## - Requires an domainname as they limit the programs for some
## Docs: http://www.kanal5play.se/api
module Shin
  module Play
    class Sbstv
      
      def new
        self
      end
      
      # Fix these before running
      def before(params={})
        raise MissingArgument, "You are missing the argument 'sbstv_domain' which is required to use this source." unless Shin.get[:sbstv_domain] != nil
        
        "http://www." + Shin.get[:sbstv_domain]
      end
      
      # Programs
      def programs
        domain = before()
        
        # Response
        response = Base.get(domain + '/api/listPrograms?format=FLASH')
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Data
        data = Oj.load(response.body) rescue nil
        
        # Multiple
        if data != nil
          data.to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end
      end
      
      # Videos
      def videos(params={})
        domain = before(params)
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""
        
        # Response
        response = Base.get(domain + '/api/listVideos?format=FLASH&programId=' + params[:id].to_s )
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Data
        data = Oj.load(response.body) rescue nil
        
        # Multiple
        if data != nil
          data.to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end
      end
      
      # Video
      def video(params={})
        domain = before(params)
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""
        
        # Response
        response = Base.get(domain + '/api/getVideo?format=FLASH&videoId=' + params[:id].to_s )
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Data
        data = Oj.load(response.body) rescue nil
        
        # Can't be nil
        if data != nil
          data.to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end
      end
      
      # Errors
      class NotValid         < StandardError; end
      class MissingArgument  < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end